package com.project.modules.redEnvelope.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.common.service.RedisService;
import com.project.modules.notice.model.TblMessage;
import com.project.modules.notice.service.TblMessageService;
import com.project.modules.quartz.EndJob;
import com.project.modules.quartz.StartJob;
import com.project.modules.redEnvelope.mapper.TblRedEnvelopeMapper;
import com.project.modules.redEnvelope.model.TblRedEnvelope;
import com.project.modules.redEnvelope.service.TblRecordService;
import com.project.modules.redEnvelope.service.TblRedEnvelopeService;
import com.project.modules.redEnvelope.service.TblSignService;
import com.project.modules.ums.model.UmsUser;
import com.project.modules.ums.service.UmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Service 实现类
 *
 * @author Qing2514
 */
@Slf4j
@Service
public class TblRedEnvelopeServiceImpl extends ServiceImpl<TblRedEnvelopeMapper, TblRedEnvelope> implements TblRedEnvelopeService {

    public static final String START = "start";
    private static final int waitUserOffset = 1;
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TblRecordService recordService;
    @Autowired
    private UmsUserService userService;
    @Autowired
    private TblMessageService messageService;
    @Autowired
    private TblRedEnvelopeService redEnvelopeService;
    @Autowired
    private TblSignService signService;

    @Override
    public void incomeAndNotice(long redId, long userId, BigDecimal money, String msg, Date date) {
        income(userId, money);
        String content = msg + money.toString() + "元";
        // 发送邮件通知
        TblMessage message = TblMessage.builder()
                .redId(redId)
                .content(content)
                .receiveUserId(userId)
                .sendTime(date)
                .sendUserId(userService.getByUsername(redEnvelopeService.getById(redId).getCreateBy()).getId())
                .isAuto(1)
                .method(2)
                .build();
        messageService.save(message);
//        TblMessage emailMessage = new TblMessage();
//        BeanUtils.copyProperties(message,emailMessage);
//        emailMessage.setMethod(2);
//        emailMessage.setId(null);
//        messageService.save(emailMessage);
        log.info(userId + msg + money);
    }

    @Override
    public void income(long userId, BigDecimal money) {
        UmsUser user = userService.getById(userId);
        user.setAccountBalance(user.getAccountBalance().add(money));
        userService.updateById(user);
    }


    @Override
    public Page<TblRedEnvelope> getPage(Long keyword, Integer pageSize, Integer pageNum) {
        Page<TblRedEnvelope> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<TblRedEnvelope> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(TblRedEnvelope::getId, keyword);
        return page(page, wrapper);
    }

    @Override
    public void scheduleStartAndEnd(Long redId, Date startTime, Date endTime) {
        try {
            scheduleStart(redId, startTime);
            // 留一定时间给用户传输时延
            scheduleEnd(redId, DateUtil.offsetSecond(endTime, waitUserOffset));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }


    private void scheduleStart(Long redId, Date time) {
        log.info("创建定时任务-通知开始抢红包" + redId + time);
        // 创建一个JobDetail，用于定义任务
        JobDetail jobDetail = JobBuilder.newJob(StartJob.class)
                .usingJobData("redId", redId)
                .build();
        // 创建一个Trigger，定义任务的执行时间
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(redId + START)
                .startAt(time)
                .build();
        // 调度任务
        try {
            scheduler.scheduleJob(jobDetail, trigger);
            TriggerKey triggerKey = new TriggerKey(redId + START, redId + START);
            log.info(scheduler.getTriggerState(triggerKey).name());
        } catch (SchedulerException e) {
            log.error("【任务执行异常】" + e.getMessage());
        }
    }

//    private void scheduleEnd(Long redId, Date time) throws SchedulerException {
//
//        // 创建一个JobDetail，用于定义任务
//        JobDetail jobDetail = JobBuilder.newJob(EndJob.class)
//                .usingJobData("redId", redId)
//                .build();
//        // 创建一个Trigger，定义任务的执行时间
//        Trigger trigger = TriggerBuilder.newTrigger()
//                .withIdentity(redId + "")
//                .startAt(time)
//                .build();
//        // 调度任务
//        scheduler.scheduleJob(jobDetail, trigger);
//    }

    private void scheduleEnd(Long redId, Date time) throws SchedulerException {
        log.info("创建定时任务-结算红包" + time);

        // 创建一个JobDetail，用于定义任务
        JobDetail jobDetail = JobBuilder.newJob(EndJob.class)
                .usingJobData("redId", redId)
                .build();
        // 创建一个Trigger，定义任务的执行时间
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(redId + "end")
                .startAt(time)
                .build();
        // 调度任务
        scheduler.scheduleJob(jobDetail, trigger);
    }


}
